//
//  ElarcScrollingNavbarViewController.swift
//  elarc01
//
//  Created by elarc on 16/6/3.
//  Copyright © 2016年 elarc. All rights reserved.
//

import UIKit

class ElarcScrollingNavbarViewController: UIViewController,UIGestureRecognizerDelegate {

    var scrollableView:UIView?
    var lastContentOffset:CGFloat?
    var panGesture:UIPanGestureRecognizer?
    var overLay:UIView?
    var isCollaspsed:Bool?
    var isExpanded:Bool?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.navigationBar.translucent = false
        lastContentOffset = 0
        // Do any additional setup after loading the view.
    }
    
    override func viewWillDisappear(animated: Bool) {
        self.navigationController?.navigationBar.translucent = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func followScrollView(scrollableView:UIView) -> Void {
        
        self.scrollableView = scrollableView
        self.panGesture = UIPanGestureRecognizer(target: self,action: #selector(ElarcScrollingNavbarViewController.handlePan(_:)))
        self.panGesture?.maximumNumberOfTouches = 1
        self.panGesture?.delegate = self
        self.scrollableView?.addGestureRecognizer(self.panGesture!)
        
        var frame:CGRect = (self.navigationController?.navigationBar.frame)!
        frame.origin = CGPointZero
        self.overLay = UIView(frame:frame)
        
        if ((self.navigationController?.navigationBar.barTintColor) == nil) {
        }
        self.overLay?.backgroundColor = self.navigationController?.navigationBar.barTintColor
        self.overLay?.userInteractionEnabled = false
        self.navigationController?.navigationBar.addSubview(self.overLay!)
        self.overLay?.alpha = 0
    }

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    func handlePan(gesture:UIPanGestureRecognizer) -> Void {
        
        let translation:CGPoint = gesture.translationInView(self.scrollableView?.superview)
        var delta:CGFloat = self.lastContentOffset! - translation.y
        self.lastContentOffset = translation.y
        
        var frame:CGRect?
        
        if delta > 0 {
            if self.isCollaspsed == true {
                return
            }
            
            frame = self.navigationController?.navigationBar.frame
            if (frame!.origin.y - delta < -24) {
                delta = frame!.origin.y + 24
            }
            
            frame!.origin.y = max(-24, frame!.origin.y - delta)
            self.navigationController!.navigationBar.frame = frame!;
            if frame?.origin.y == -24 {
                self.isCollaspsed = true
                self.isExpanded = false
            }
            
            updateSizingWithDelta(delta)
            if self.scrollableView!.isKindOfClass(UIScrollView.classForCoder()) {
               (self.scrollableView as! UIScrollView).setContentOffset(CGPointMake((self.scrollableView as? UIScrollView)!.contentOffset.x, (self.scrollableView as? UIScrollView)!.contentOffset.y - delta), animated: true)
            }
            
        }
        
        if delta < 0 {
            if self.isExpanded == true {
                return
            }
            
            frame = self.navigationController!.navigationBar.frame;
            
            if (frame!.origin.y - delta) > 20 {
                delta = frame!.origin.y - 20
            }
            frame!.origin.y = min(20, frame!.origin.y - delta)
            self.navigationController!.navigationBar.frame = frame!
            
            if frame!.origin.y == 20 {
                self.isExpanded = true
                self.isCollaspsed = false
            }
            
           updateSizingWithDelta(delta)
        }
        
        if gesture.state == UIGestureRecognizerState.Ended {
            self.lastContentOffset = 0
            checkForPartialScroll()
        }
    }
    
    func checkForPartialScroll() -> Void {
        
        let pos:CGFloat = self.navigationController!.navigationBar.frame.origin.y;
        
        // Get back down
        if pos >= -2 {
            
            UIView.animateWithDuration(0.2, animations: {
                var frame:CGRect = self.navigationController!.navigationBar.frame
                let delta:CGFloat = frame.origin.y - 20;
                frame.origin.y = min(20, frame.origin.y - delta);
                self.navigationController!.navigationBar.frame = frame;
                
                self.isExpanded = true
                self.isCollaspsed = false
                
              self.updateSizingWithDelta(delta)
            })
            
        } else {
            // And back up
            
            UIView.animateWithDuration(0.2, animations: {
                var frame:CGRect = self.navigationController!.navigationBar.frame
                let delta:CGFloat = frame.origin.y + 24
                frame.origin.y = max(-24, frame.origin.y - delta)
                self.navigationController!.navigationBar.frame = frame
                
                self.isExpanded = false
                self.isCollaspsed = true
                self.updateSizingWithDelta(delta)
            })
        
        }
    }
    
    
    func updateSizingWithDelta(delta:CGFloat) -> Void {
        var frame:CGRect = self.navigationController!.navigationBar.frame
        
        let alpha:CGFloat = (frame.origin.y + 24) / frame.size.height
        self.overLay?.alpha = 1-alpha
        self.navigationController!.navigationBar.tintColor = self.navigationController!.navigationBar.tintColor .colorWithAlphaComponent(alpha)
        
        frame = self.scrollableView!.superview!.frame
        frame.origin.y = self.navigationController!.navigationBar.frame.origin.y + self.navigationController!.navigationBar.frame.size.height;
        frame.size.height = frame.size.height + delta
        self.scrollableView!.superview!.frame = frame
        
        // Changing the layer's frame avoids UIWebView's glitchiness
        frame = self.scrollableView!.layer.frame
        frame.size.height += delta;
        self.scrollableView!.layer.frame = frame
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
